import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/pages/Mine/cn_about.dart';
import 'package:flutter_application_cyber/pages/Mine/cn_blockList.dart';
import 'package:flutter_application_cyber/pages/Mine/cn_coinStore_Page.dart';
import 'package:flutter_application_cyber/pages/Mine/cn_editProfile.dart';
import 'package:flutter_application_cyber/pages/Mine/cn_setting_page.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:provider/provider.dart';
import 'package:flutter_application_cyber/model/cn_ossPolic_model.dart';
import 'package:flutter_application_cyber/model/cn_object_cache.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
import '../../model/cn_strategy_model.dart';
import 'package:flutter_application_cyber/model/cn_strategy_vmodel.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:flutter_application_cyber/tools/cn_log_manger.dart';
import 'package:flutter_application_cyber/tools/cn_log_pv_manger.dart';
import 'package:flutter_application_cyber/tools/cn_event_bus.dart';
import 'package:flutter_application_cyber/tools/cn_event_busUtils.dart';
import 'dart:async';

class CnMinePage extends StatefulWidget {
  const CnMinePage({Key? key}) : super(key: key);

  @override
  State<CnMinePage> createState() => _MinePageState();
}

class _MinePageState extends State<CnMinePage> {
  var titleArr = ['Customer Service', 'Blocked list', 'About', 'Setting'];
  var imageArr = [
    'images/icon_customer_mine.png',
    'images/icon_blocked_mine.png',
    'images/icon_about_mine.png',
    'images/icon_setting_mine.png'
  ];
    StreamSubscription? event;


  UserInfoModel getUserInfo() {
    return Provider.of<ChangeUserInfoModel>(context, listen: true).info;
  }

  int availableCoins = 0;

  CnStrategyModel getStrategy() {
    return CnStrategyViewModel.getInfo().strategy!;
  }
  _reloadInfoData() {
    CnNetHelper.getUserInfo('',
        (HDHResponseData configData, bool result, String msg) async {
      if (result) {
        UserInfoModel userModel = UserInfoModel.fromJson(configData.data);
        Provider.of<ChangeUserInfoModel>(context, listen: false)
            .setInfo(userModel);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('images/icon_page_bg_1.png'),
                  fit: BoxFit.fill),
            ),
            child: Column(children: <Widget>[
              Container(
                height: 250,
                width: MediaQuery.of(context).size.width,
                // color: Colors.green,
                child: Column(children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      InkWell(
                        onTap: () async {
                          //编辑
                          var result = await Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => const CnEditProfile()));
                          if (result != null) {
                            _reloadInfoData();
                          }
                        },
                        child: Container(
                          margin: EdgeInsets.only(right: 18, top: 60),
                          width: 32,
                          height: 32,
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image:
                                      AssetImage('images/icon_edit_mine.png'))),
                        ),
                      )
                    ],
                  ),
                  InkWell(
                    onTap: () async {
                      CnLogPvManger.stat(
                          page: 'editavatar',
                          subPage: 'subPage',
                          terPage: 'terPage',
                          broadcasterId: 'broadcasterId');

                      bool isOpenPhotos = await requestCameraPermission();
                      if (isOpenPhotos) {
                        XFile? pickedImage = await ImagePicker().pickImage(
                            source: ImageSource.gallery,
                            imageQuality: 70,
                            maxHeight: 100,
                            maxWidth: 100);
                        if (pickedImage != null) {
                          final File file = File(pickedImage.path);
                          _postUploadImageToOssWithImage(file);
                        }
                      } else {
                        _showCameraDialog(context);
                      }
                    },
                    child: Stack(
                      clipBehavior: Clip.none,
                      children: [
                        Container(
                          clipBehavior: Clip.hardEdge,
                          width: 88,
                          height: 88,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(44),
                          ),
                          child: getUserInfo().avatarUrl != null
                              ? Image.network(getUserInfo().avatarUrl!,
                                  fit: BoxFit.cover)
                              : Image.asset('images/icon_logo.png'),
                        ),
                        Positioned(
                            top: 60,
                            left: 60,
                            child: Container(
                              width: 28,
                              height: 28,
                              child: Image.asset('images/icon_photo_mine.png'),
                            ))
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 16),
                    child: Text(
                      getUserInfo().nickname ?? '',
                      style: TextStyle(color: Colors.white, fontSize: 18),
                    ),
                  )
                ]),
              ),
              InkWell(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const CnCoinStorePage(
                              isPodPage: false,
                            )),
                  );
                },
                child: Container(
                  height: 70,
                  width: 302,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage('images/icon_coin_bg_mine.png'),
                          fit: BoxFit.fill)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Container(
                            margin: EdgeInsets.only(left: 10, right: 10),
                            width: 47,
                            height: 45,
                            child:
                                Image.asset('images/icon_coins_logo_mine.png'),
                          ),
                          const Text(
                            'My Coins',
                            style: TextStyle(
                                color: Color(0xFFEA248F), fontSize: 16),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Text(
                            '${availableCoins}',
                            style: TextStyle(
                                color: Color(0xFFEA248F),
                                fontSize: 30,
                                fontWeight: FontWeight.bold),
                          ),
                          Container(
                            margin: EdgeInsets.only(left: 10, right: 10),
                            width: 18,
                            height: 18,
                            child: Image.asset('images/icon_rightRow_mine.png'),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                height: 250,
                child: ListView.builder(
                    physics: NeverScrollableScrollPhysics(),
                    padding: EdgeInsets.only(top: 20, left: 50, right: 50),
                    itemCount: titleArr.length,
                    itemBuilder: (context, index) {
                      return Container(
                          height: 50,
                          child: InkWell(
                            onTap: () {
                              switch (index) {
                                case 0: //customer

                                  Map arg = {
                                    "coversationType":
                                        RCIMIWConversationType.private,
                                    "targetId":
                                        getStrategy().userServiceAccountId,
                                    'nickName': '',
                                  };
                                  Navigator.pushNamed(context, "/conversation",
                                      arguments: arg);

                                  CnLogPvManger.stat(
                                      page: 'customer',
                                      subPage: 'subPage',
                                      terPage: 'terPage',
                                      broadcasterId: 'broadcasterId');

                                  break;
                                case 1: //blocklist
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            const CnBlockList()),
                                  );
                                  break;
                                case 2: //about
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            const CnAboutPage()),
                                  );
                                  break;
                                case 3: //setting
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            const CnSettingPage()),
                                  );
                                  break;
                                default:
                              }
                            },
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      margin:
                                          EdgeInsets.only(left: 0, right: 10),
                                      width: 18,
                                      height: 18,
                                      child: Image.asset(imageArr[index]),
                                    ),
                                    Text(
                                      titleArr[index],
                                      style: TextStyle(
                                          color: Color(0xCCFFFFFF),
                                          fontSize: 18),
                                    ),
                                  ],
                                ),
                                Container(
                                  width: 18,
                                  height: 18,
                                  margin: EdgeInsets.only(right: 0),
                                  child: Image.asset(
                                      'images/icon_rightRow_mine.png'),
                                )
                              ],
                            ),
                          ));
                    }),
              )
            ])));
  }

  @override
  void initState() {
    super.initState();
    _getOssPolicyData();
    getCoins();
    event = EventBusUtils.getInstance()?.on().listen((event){
     if (event.toString() == EventKeys.applePaySuccess) {
        getCoins();
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    event?.cancel();
  }

  void getCoins() {
    CnNetHelper.getUserCoins().then((value) {
            print(1000);

      setState(() {
        availableCoins = value;
      });
    });
  }

  _getOssPolicyData() async {
    CnOssPolicModel? ossPolicyData = await CnNetHelper.getOssPolicyData();
    if (ossPolicyData != null) {
      CnObjectCache.getInfo().ossPolicModel = ossPolicyData;
    }
  }

  //上传大头像
  _postUploadImageToOssWithImage(File imagePath) {
    DateTime dateTime = DateTime.now();
    String fileName = imagePath.path.split('/').last;
    String format = fileName.split('.').last;
    int imageTimeName = dateTime.millisecondsSinceEpoch +
        (dateTime.microsecondsSinceEpoch ~/ 1000000);
    String imageName = '$imageTimeName.$format';

    String dir = CnObjectCache.getInfo().ossPolicModel.dir;

    var params = {
      'ossaccessKeyId': CnObjectCache.getInfo().ossPolicModel.accessKeyId,
      'policy': CnObjectCache.getInfo().ossPolicModel.policy,
      'signature': CnObjectCache.getInfo().ossPolicModel.signature,
      'callback': CnObjectCache.getInfo().ossPolicModel.callback,
      'key': '$dir/$imageName',
    };
    EasyLoading.show(status: 'loading...');

    CnNetHelper.postUploadImageToOssWithImage(
        CnObjectCache.getInfo().ossPolicModel.host,
        params,
        imagePath.path,
        '$dir/$imageName', (HDHResponseData resp, bool result, String msg) {
      EasyLoading.dismiss();

      if (result) {
        print(resp.data);
        var param = {'avatarPath': resp.data['filename']};
        CnNetHelper.updateAvatar(param,
            (HDHResponseData resp, bool result, String msg) {
          if (result) {
            _reloadInfoData();
          }
        });
      }
    });
  }

  Future<bool> requestCameraPermission() async {
    //获取当前的权限
    var status = await Permission.photos.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.photos.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  void _showCameraDialog(context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          contentPadding:
              const EdgeInsets.only(top: 4, left: 24, right: 24, bottom: 0),
          title: const Text('Prompt'),
          content: Container(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const SizedBox(height: 16),
                const Text(
                  'System permission camera.write external storage access denied',
                  style: const TextStyle(fontSize: 18, color: Colors.black),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 20, left: 0, right: 0),
                  height: 1,
                  color: Colors.black12,
                ),
                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Container(
                        child: InkWell(
                          onTap: () {
                            //复制
                            Navigator.of(context).pop();
                          },
                          child: Container(
                            height: 40,
                            alignment: Alignment.center,
                            child: const Text('Later',
                                style: TextStyle(
                                    color: Colors.black, fontSize: 18)),
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 0),
                        width: 1,
                        height: 46,
                        color: Colors.black12,
                      ),
                      Container(
                        child: InkWell(
                          onTap: () {
                            Navigator.of(context).pop();
                            // 打开手机上该app权限的页面
                            openAppSettings();
                          },
                          child: Container(
                            height: 40,
                            alignment: Alignment.center,
                            child: const Text('Go Settings',
                                style: TextStyle(
                                    color: Colors.black, fontSize: 18)),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
